from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import csv

driver = webdriver.Chrome()
driver.get('https://emweb.securities.eastmoney.com/pc_hsf10/pages/index.html?type=web&code=SH688235&color=b#/gsds/dzjy')
wait = WebDriverWait(driver, 20)

for i in range(2, 8):
    trade_time = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[1]'.format(i)))).text
    chengjiaojia = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[2]'.format(i)))).text
    zhe_or_yi = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[3]'.format(i)))).text
    chengjiaoliang = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[4]'.format(i)))).text
    chengjiaojinge = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[5]'.format(i)))).text
    mairu = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[6]'.format(i)))).text
    maichu = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div[4]/div/div[7]/div[2]/table/tr[{}]/td[7]'.format(i)))).text

    print(trade_time, chengjiaojia, zhe_or_yi, chengjiaoliang, chengjiaojinge, mairu, maichu)
    data = {
        '交易日期': trade_time,
        '成交价(元)': chengjiaojia,
        '折/溢价率(%)': zhe_or_yi,
        '成交量(股)': chengjiaoliang,
        '成交金额(元)': chengjiaojinge,
        '买入营业部': mairu,
        '卖出营业部': maichu
    }
    with open('股票信息.csv', 'a', encoding='utf-8', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=['交易日期', '成交价(元)', '折/溢价率(%)', '成交量(股)', '成交金额(元)', '买入营业部', '卖出营业部'])
        writer.writerow(data)

driver.close()